package com.test.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.test.dao.DictionRepository;
import com.test.entities.Diction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.ServerEndpoint;

//@Component
public class SendMail {

    @Autowired
    private DictionRepository dictionRepository;

    public static SendMail sendMail;

    public static SendMail instance = null;

    public SendMail() {

    }

    //在方法上加上注解@PostConstruct，保证Bean初始化前已经装配了属性（注：Bean初始化包括，实例化Bean，并装配Bean的属性（依赖注入））
    //@PostConstruct
    public void init() {
        sendMail = this;
    }


    public static SendMail getInstance() {
        if (instance == null) {
            instance = new SendMail();
        }
        return instance;
    }

    public void send(String content,String title) {
        try {
            String to[]={getMailList()};
            //to[0] = getMailList();
            Properties p = new Properties(); //Properties p = System.getProperties();
            p.put("mail.smtp.auth", "true");
            p.put("mail.transport.protocol", "smtp");
            p.put("mail.smtp.host", "smtp.163.com");
            p.put("mail.smtp.port", "25");
            //建立会话     
            Session session = Session.getInstance(p);
            Message msg = new MimeMessage(session); //建立信息     

            msg.setFrom(new InternetAddress("testingresult@163.com")); //发件人

            String toList = getMailList(to);
            InternetAddress[] iaToList = new InternetAddress().parse(toList);

            msg.setRecipients(Message.RecipientType.TO,iaToList); //收件人     

            msg.setSentDate(new Date()); // 发送日期
            msg.setContent(content, "text/html;charset=UTF-8");
            msg.setSubject(title); // 主题
            //msg.setText(content); //内容
            // 邮件服务器进行验证     
            Transport tran = session.getTransport("smtp");
            tran.connect("smtp.163.com", "testingresult", "testingresult123");
            // bluebit_cn是用户名，xiaohao是密码     
            tran.sendMessage(msg, msg.getAllRecipients()); // 发送     
            System.out.println("邮件发送成功");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getMailList(String[] mailArray){

        StringBuffer toList = new StringBuffer();
        int length = mailArray.length;
        if(mailArray!=null && length <2){
            toList.append(mailArray[0]);
        }else{
            for(int i=0;i<length;i++){
                toList.append(mailArray[i]);
                if(i!=(length-1)){
                    toList.append(",");
                }

            }
        }
        return toList.toString();

    }



    public static String getMailList(){
        //String data = HttpUtil.doPost("http://127.0.0.1:8000/api/persons/findDiction","application/json;charset=UTF-8","","key=mailList");

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //System.out.println(request.getServerName());
        //System.out.println(request.getServerPort());
        //String data = HttpUtil.doPost("http://127.0.0.1:8000/api/persons/findDiction","application/json;charset=UTF-8","","key=mailList");
        String port = "";
//        if(request.getServerName().indexOf("127.0.0.1") > -1 || (request.getServerName()).indexOf("localhost") > -1)
//            port = "8080";
//        else
//            port = "8000";
        port = "8000";
        String data = HttpUtil.doPost("http://"+request.getServerName()+":"+port+"/api/persons/findDiction","application/json;charset=UTF-8","","key=mailList");
        Diction diction = JSON.parseObject(data, new TypeReference<Diction>() {});
        return diction.getDictionValue();
    }

    public static void main(String[] args){
        //new TestMail().send();
        //new SendMail().dictionRepository.findAll();

}
    public static void doSomething4SendMail(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        System.out.println("重新校验生成数据");
        HttpUtil.doGet("http://"+request.getServerName()+":"+request.getServerPort()+"/api/persons/testJob","","");
        System.out.println("发送邮件");
        HttpUtil.doGet("http://"+request.getServerName()+":"+request.getServerPort()+"/api/persons/genReport","","");
    }


}   